package com.example.Servlet;

import com.example.Service.CommentService;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "LikeCommentServlet", value = "/LikeCommentServlet")
public class LikeCommentServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应类型和编码
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");

        String commentId = request.getParameter("commentId"); // 修正参数名
        String action = request.getParameter("action"); // like 或 unlike
        Map<String, Object> result = new HashMap<>();

        try {
            if (commentId == null || commentId.trim().isEmpty()) {
                result.put("code", 400);
                result.put("msg", "评论ID不能为空");
            } else {
                // 调用Service层更新点赞数
                CommentService commentService = new CommentService(); // 修正变量名
                boolean success;

                if ("unlike".equals(action)) {
                    // 取消点赞
                    success = commentService.decrementCommentLikes(Integer.parseInt(commentId)); // 修正变量名
                    result.put("msg", "取消点赞成功");
                } else {
                    // 点赞
                    success = commentService.incrementCommentLikes(Integer.parseInt(commentId)); // 修正变量名和方法调用
                    result.put("msg", "点赞成功");
                }

                if (success) {
                    result.put("code", 200); // 添加分号
                    // 返回更新后的点赞数
                    int currentLikes = commentService.getCommentLikes(Integer.parseInt(commentId)); // 修正变量名
                    result.put("likes", currentLikes);
                } else {
                    result.put("code", 500);
                    result.put("msg", "操作失败");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", "服务器错误: " + e.getMessage());
        }

        // 返回JSON响应
        Gson gson = new Gson();
        response.getWriter().write(gson.toJson(result));
    }
}